package itsm.isperp.module.service.sparepart;

import java.util.Map;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.sparepart.SptSparepartRelation;
import itsm.isperp.module.repository.sparepart.SptSparepartRelationMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 服务
 * 
 * @author lizx
 * @date 2016-04-21 18:38
 */
@Service
public class SptSparepartRelationService extends BaseService<SptSparepartRelation> {

	@Autowired
	protected SptSparepartRelationMapper sptSparepartRelationMapper;

	@Override
	public SptSparepartRelationMapper getRepository() {
		return this.sptSparepartRelationMapper;
	}

	public void deleteByCiId(String ciId, String typeKey) {
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		String sql = "delete from spt_sparepart_relation where ci_id='" + ciId + "' and type_key='" + typeKey + "'";
		jdbcTemplate.execute(sql);
	}
	
	public void deleteByCiIdAndsptId(String ciId, String sparepartId) {
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    String sql = "delete from spt_sparepart_relation where ci_id='" + ciId + "' and sparepart_id='" + sparepartId + "'";
    jdbcTemplate.execute(sql);
  }

	public DataResponse<Map<String, Object>> findCiSparepart(JqGridRequest req) {
		return this.sptSparepartRelationMapper.findCiSparepart(req);
	}
	
	public static void updateSptSparepart(String sparepartId) {
	  JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    String sql="DELETE FROM spt_sparepart WHERE id IN(SELECT ci_id FROM spt_sparepart_relation WHERE sparepart_id='"+sparepartId+"')";
    String sql2="INSERT INTO spt_sparepart SELECT CODE,CODE,NAME,model,unit,min_stock,min_stock_use_rule,min_stock_use_rule_proportion,min_stock_use_rule_desc,amount,spt_sparepart_category_id,in_stock_quantity,out_stock_quantity,back_stock_quantity,discard_quantity,creator,creator_name,create_date,MODIFIER,modifier_name,modify_date,devide_number,stock_in_date,use_staff_id,use_staff_name,support_staff_id,support_staff_name,manufacturer,manufacturer_provider_id,manufacturer_provider_name,STATUS,project_id,project_name,remark,sn,use_status,location,price FROM spt_sparepart_plan WHERE code IN(SELECT ci_id FROM spt_sparepart_relation WHERE sparepart_id='"+sparepartId+"') and relation_id='"+sparepartId+"'";
    jdbcTemplate.batchUpdate(sql,sql2);
  }

}
